﻿namespace Core.Domain
{
	using System.Diagnostics.Contracts;
	using Infrastructure;

	public class RegistrationService
	{
		public RegistrationService(IDomainSessionFactory domainSessionFactory)
		{
			CodeContract.Requires(domainSessionFactory != null);
			this.DomainSessionFactory = domainSessionFactory;			
		}

		public IDomainSessionFactory DomainSessionFactory
		{
			get; 
			private set;
		}

		public RegistrationResult Register(string email, string displayName, string password)
		{
			using (var session = this.DomainSessionFactory.Create())
			{
				if (session.AccountRepository.ContainsWithEmail(email))
				{
					return RegistrationResult.FailedResult(RegistrationResultCode.AccountWithEmailExists);
				}

				// TODO Check name dublicatess

				Person candidatePerson =
					new Person
						{
							EmailAddress = email,
							DisplayName = displayName
						};

				session.PersonRepository.Save(candidatePerson);

				Account candidateAccount =
					new Account
						{
							Password = password,
							Person = candidatePerson
						};

				session.AccountRepository.Save(candidateAccount);

				session.Flash();

				return RegistrationResult.SuccessfullResult(candidateAccount);
			}
		}
	}
}
